/*
JS Modified from a tutorial found here: 
http://www.inwebson.com/html5/custom-html5-video-controls-with-jquery/

I really wanted to learn how to skin html5 video.
*/
define(function(require, exports, module) {
  //INITIALIZE
  exports.initMp3 = initMp3;
  exports.startPlay = startPlay;
  exports.playpause = playpause;

  var video;

  var plusAudio = null,
    pi = null, //播放定时器，检测进度
    d = 0, //音乐时长
    c = 0, //当前文件
    playFlag = false; //当前状态，true 正在播放 false 暂停

  /*  var tp = 2;            //传入参数区分当前播放的是本地还是网页url,tp=1本地，tp=2 网页
    var url = "http://sc1.111ttt.com/2017/4/05/10/298101104389.mp3"      //传入网页url*/

  var tp = 1;
  var url = ''; // "_www/audio/friendship.mp3" //传入本地url

  function initMp3(type) {
    type = type || 2;

    // console.log("initMp3 in");
    video = $('.myVideo');
    tp = type; //添加dcloud 播放 1、docloud 2、网页url

    if (video[0] == undefined) {
      console.error("not find video");
      return;
    }
    $('.myVideo').unbind();
    $('.btnPlay').unbind();
    $('.btnFS').unbind();
    $('.sound').unbind();
    $('.progress').unbind();
    $('.volume').unbind();

    //remove default control when JS loaded
    video[0].removeAttribute("controls");
    $('.control').fadeIn(500);
    $('.caption').fadeIn(500);
    if (tp == 1) {
      console.log("点击了播放");
      // if (window.plus) {  //频闭dcloud 自动播放.
      //   plusReady();
      // } else {
      //   document.addEventListener('plusready', plusReady, false);
      // }
    } else {
      //before everything get started
      video.on('loadedmetadata', function() {

        //set video properties
        $('.current').text(timeFormat(0));
        $('.duration').text(timeFormat(video[0].duration));
        updateVolume(0, 0.7);

        //start to get video buffering data 
        setTimeout(startBuffer, 150);

        //bind video events
        $('.videoContainer')
          // .hover(function() { //屏蔽,手机端用不上.
          //     $('.control').stop().fadeIn();
          //     $('.caption').stop().fadeIn();
          // }, function() {
          //     if (!volumeDrag && !timeDrag) {
          //         // $('.control').stop().fadeOut();
          //         // $('.caption').stop().fadeOut();
          //     }
          // })
          .on('click', function() {
            $('.btnPlay').find('.icon-play').addClass('icon-pause').removeClass('icon-play');
            $(this).unbind('click');
            video[0].play();
          });
      });
    }

    //display current video play time
    video.on('timeupdate', function() {
      var currentPos = video[0].currentTime;
      var maxduration = video[0].duration;
      var perc = 100 * currentPos / maxduration;
      $('.timeBar').css('width', perc + '%');
      $('.current').text(timeFormat(currentPos));
    });
    //CONTROLS EVENTS
    //video screen and play button clicked
    video.on('click', function() { playpause(tp); });
    $('.btnPlay').on('click', function() {
      playpause(tp);
      console.log("btnPlay click")
    });

    //fullscreen button clicked
    $('.btnFS').on('click', function() {
      if ($.isFunction(video[0].webkitEnterFullscreen)) {
        video[0].webkitEnterFullscreen();
      } else if ($.isFunction(video[0].mozRequestFullScreen)) {
        video[0].mozRequestFullScreen();
      } else {
        alert('Your browsers doesn\'t support fullscreen');
      }
    });

    //sound button clicked
    $('.sound').click(function() {
      if (tp == 1) {
        $(this).toggleClass('muted');
        if (plus.device.getVolume() > 0) {
          plus.device.setVolume(0);
        } else {
          plus.device.setVolume(0.5);
        }
      } else {
        video[0].muted = !video[0].muted;
        $(this).toggleClass('muted');
        if (video[0].muted) {
          $('.volumeBar').css('width', 0);
        } else {
          $('.volumeBar').css('width', video[0].volume * 100 + '%');
        }
      }
    });

    //VIDEO EVENTS
    //video canplay event
    video.on('canplay', function() {
      $('.loading').fadeOut(100);
    });
    video.on('canplaythrough', function() {
      completeloaded = true;
    });

    //video ended event
    video.on('ended', function() {
      $('.btnPlay').removeClass('paused');
      video[0].pause();
    });

    //video seeking event
    video.on('seeking', function() {
      //if video fully loaded, ignore loading screen
      if (!completeloaded) {
        $('.loading').fadeIn(200);
      }
    });

    //video seeked event
    video.on('seeked', function() {});

    //video waiting for more data event
    video.on('waiting', function() {
      $('.loading').fadeIn(200);
    });
    $('.progress').on('mousedown touchstart', function(e) {
      timeDrag = true;
      updatebar(e.pageX || e.originalEvent.changedTouches[0].pageX);
    });
    $(document).on('mouseup touchend', function(e) {
      if (timeDrag) {
        timeDrag = false;
        updatebar(e.pageX || e.originalEvent.changedTouches[0].pageX);
      }
    });
    $(document).on('mousemove touchmove', function(e) {
      // console.log('touchmove');
      if (timeDrag) {
        updatebar(e.pageX || e.originalEvent.changedTouches[0].pageX);
      }
    });
    $('.volume').on('mousedown touchstart', function(e) {
      volumeDrag = true;
      video[0].muted = false;
      $('.sound').removeClass('muted');
      updateVolume(e.pageX || e.originalEvent.changedTouches[0].pageX);
    });
    $(document).on('mouseup touchend', function(e) {
      if (volumeDrag) {
        volumeDrag = false;
        updateVolume(e.pageX || e.originalEvent.changedTouches[0].pageX);
      }
    });
    $(document).on('mousemove touchmove', function(e) {
      if (volumeDrag) {
        updateVolume(e.pageX || e.originalEvent.changedTouches[0].pageX);
      }
    });

  }

  //display video buffering bar
  var startBuffer = function() {
    try {
      var currentBuffer = video[0].buffered.end(0);
      var maxduration = video[0].duration;
      var perc = 100 * currentBuffer / maxduration;
      $('.bufferBar').css('width', perc + '%');

      if (currentBuffer < maxduration) {
        setTimeout(startBuffer, 500);
      }
    } catch (e) {
      console.log("thinkido add; 不影响");
    }
  };

  function playpause(type) {
    type = type || 2; //默认为2 播放网页音乐
    if (type == 2) {
      if (video[0].paused || video[0].ended) {
        $('.btnPlay').addClass('paused');
        $('.btnPlay').find('.icon-play').addClass('icon-pause').removeClass('icon-play');
        video[0].play();
      } else {
        $('.btnPlay').removeClass('paused');
        $('.btnPlay').find('.icon-pause').removeClass('icon-pause').addClass('icon-play');
        video[0].pause();
      }
    } else {
      console.log("plusAudio" + plusAudio);
      if (!plusAudio) {
        return false;
      }
      var getDuration = plusAudio.getDuration();
      if (playFlag && plusAudio.getPosition() < getDuration) {
        console.log("暂停");
        playFlag = false;
        $('.btnPlay').removeClass('paused');
        $('.btnPlay').find('.icon-pause').removeClass('icon-pause').addClass('icon-play');
        plusAudio.pause();
      } else if (plusAudio.getPosition() == getDuration) {
        console.log("重新开始");
        startPlay(); // startPlay(url);
      } else if (!playFlag && plusAudio.getPosition() < getDuration) {
        console.log("继续");
        playFlag = true;
        $('.btnPlay').addClass('paused');
        $('.btnPlay').find('.icon-play').addClass('icon-pause').removeClass('icon-play');
        plusAudio.resume();
      }
    }
  };

  //video canplaythrough event
  //solve Chrome cache issue
  var completeloaded = false;

  //VIDEO PROGRESS BAR
  //when video timebar clicked
  var timeDrag = false; /* check for drag event */

  var updatebar = function(x) {
    var progress = $('.progress');

    //calculate drag position
    //and update video currenttime
    //as well as progress bar
    var position = x - progress.offset().left;
    var percentage = 100 * position / progress.width();
    if (percentage > 100) {
      percentage = 100;
    }
    if (percentage < 0) {
      percentage = 0;
    }
    //根据是播放本地还是网页判断处理
    if (tp == 1) {
      if (!plusAudio) {
        return;
      }
      var getDuration = plusAudio.getDuration();
      if (!playFlag && plusAudio.getPosition() < getDuration) {
        playFlag = true;
        $('.btnPlay').addClass('paused');
        $('.btnPlay').find('.icon-play').addClass('icon-pause').removeClass('icon-play');
        plusAudio.resume();
      }
      plusAudio.seekTo(getDuration * percentage / 100);

    } else {
      var maxduration = video[0].duration;
      $('.timeBar').css('width', percentage + '%');
      video[0].currentTime = maxduration * percentage / 100;
    }
  };

  //VOLUME BAR
  //volume bar event
  var volumeDrag = false;

  var updateVolume = function(x, vol) {
    var volume = $('.volume');
    var percentage;
    //if only volume have specificed
    //then direct update volume
    if (vol) {
      percentage = vol * 100;
    } else {
      var position = x - volume.offset().left;
      percentage = 100 * position / volume.width();
    }

    if (percentage > 100) {
      percentage = 100;
    }
    if (percentage < 0) {
      percentage = 0;
    }

    //update volume bar and video volume
    $('.volumeBar').css('width', percentage + '%');
    video[0].volume = percentage / 100;

    //change sound icon based on volume
    if (video[0].volume == 0) {
      $('.sound').removeClass('sound2').addClass('muted');
    } else if (video[0].volume > 0.5) {
      $('.sound').removeClass('muted').addClass('sound2');
    } else {
      $('.sound').removeClass('muted').removeClass('sound2');
    }

  };

  //Time format converter - 00:00
  var timeFormat = function(seconds) {
    var m = Math.floor(seconds / 60) < 10 ? "0" + Math.floor(seconds / 60) : Math.floor(seconds / 60);
    var s = Math.floor(seconds - (m * 60)) < 10 ? "0" + Math.floor(seconds - (m * 60)) : Math.floor(seconds - (m * 60));
    return m + ":" + s;
  };

  /**
   * plus环境
   */
  // function plusReady() {
  //   startPlay();
  // }

  function startPlay(audioUrl) {
    if (audioUrl) {
      url = audioUrl;
    }
    if (plusAudio) {
      plusAudio.stop();
      plusAudio = null;
    }
    playFlag = true;
    plusAudio = plus.audio.createPlayer(url);
    $('.btnPlay').addClass('paused');
    $('.btnPlay').find('.icon-play').addClass('icon-pause').removeClass('icon-play');
    plusAudio.play(function() {
      playFlag = false;
      console.log("播放完毕后执行")
      $('.timeBar').css('width', '0');
      $('.btnPlay').removeClass('paused');
      $('.btnPlay').find('.icon-pause').removeClass('icon-pause').addClass('icon-play');
      if (pi) {
        clearInterval(pi);
      }
    });

    d = plusAudio.getDuration();
    pi = setInterval(function() {

      d = plusAudio.getDuration();
      c = plusAudio.getPosition();
      var perc = 100 * c / d;
      $('.timeBar').css('width', perc + '%');
      if (c == d) {
        console.log("定时器执行");
        playFlag = false;
        $('.timeBar').css('width', '0');
        $('.btnPlay').removeClass('paused');
        $('.btnPlay').find('.icon-pause').removeClass('icon-pause').addClass('icon-play');
        clearInterval(pi);
      }
    }, 1000);
  }

});
